package com.heyun.service.impl;

import com.heyun.constant.Constants;
import com.heyun.entity.dto.SignInDTO;
import com.heyun.entity.enums.MyEnum;
import com.heyun.entity.pojo.Grades;
import com.heyun.entity.pojo.CheckPOJO;
//import com.heyun.entity.pojo.SubjectPOJO;
import com.heyun.entity.vo.Homework;
import com.heyun.entity.vo.SignIn;
import com.heyun.entity.vo.StudentOfClass;
import com.heyun.entity.vo.SubjectVO;
import com.heyun.mapper.StudentMapper;
import com.heyun.mapper.TeacherMapper;
import com.heyun.service.TeacherService;
import com.heyun.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Arrays;
import java.util.Map;

@Slf4j
@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private StudentMapper studentMapper;

    /**
     * 教师获取学生信息
     *
     * @param classId
     * @return
     */
    @Override
    public StudentOfClass[] getAllStudentByClass(String classId) {
        StudentOfClass[] res = teacherMapper.getStudentByClass(classId);
        if (res.length > 0) {
            Grades[] grades = teacherMapper.getStudentsGrades(classId);
            for (int i = 0; i < res.length; i++) {
                res[i].setGrades(grades[i]);
            }
        }
        return res;
//        return ;
//        return studentByClass;
    }

    /**
     * 教师发布作业，实时更新到数据库
     *
     * @param homework
     * @return
     */
    @Override
    public int pubHomeworks(Homework homework) {
        homework.setStatus(String.valueOf(MyEnum.NotSubmitted));
        if (!(homework.getEndline() != null && homework.getHomeworkId() != null ))
            return -2;
        Map<String, Object> claims = ThreadLocalUtil.get();
        String userId = claims.get("id").toString();
        CheckPOJO[] subs = teacherMapper.getCheckPOJOsOfTeacher(userId);
        boolean contains = containsSubjectId(subs, homework.getHomeworkId(), 0);
        homework.setUserId(userId);
        homework.setTotalGrade(100.0);
        if (contains) { // 判断所选的科目是否是自己所管理的是的话就插入，否则返回-1
            int nums = teacherMapper.pubHomeworks(homework);
            SignIn si = new SignIn();
            si.setUserId(homework.getUserId());
            si.setSubjectId(homework.getHomeworkId().replace("homework","wenhua"));
            int num = teacherMapper.updateTotalPoints(si,100.0);
            System.out.println("num="+num);
            log.info(Constants.PUB_HOMEWORK_SUCCESS + "： " + nums);
            return nums;
        }
        log.info("用户【" + homework.getUserId() + "】试图发布【" + homework.getHomeworkId() + "】的课程作业，但是" + Constants.PERMISSION_DENIED);
        return -1;
    }


    /**
     * 发布签到
     *
     * @param signIn
     * @return
     */
    @Override
    public SignInDTO pubSignIn(SignIn signIn) {
        SignInDTO signInDTO = new SignInDTO();
        signIn.setStatus(String.valueOf(MyEnum.absent));
        if (signIn.getSubjectId() == null) {
            signInDTO.setResCode(-1);
            return signInDTO;
        }
        Map<String, Object> claims = ThreadLocalUtil.get();
        String userId = claims.get("id").toString();
        signIn.setUserId(userId);
        CheckPOJO[] subs = teacherMapper.getCheckPOJOsOfTeacher(userId);
        boolean contains = containsSubjectId(subs, signIn.getSubjectId(), 1);
        if (contains) {
            int nums = teacherMapper.pubSigns(signIn);
            if (nums > 0) {
                SignIn[] signs = teacherMapper.getSignInStudent(signIn.getSubjectId());
                teacherMapper.updateTotalPoints(signIn, 10.0);
                log.info(Constants.PUB_SIGN_IN_SUCCESS + "：" + nums);
                signInDTO.setSignIns(signs);
                signInDTO.setResCode(nums);
                return signInDTO;
            }
        }
        signInDTO.setResCode(-1);
        return signInDTO;
    }

    @Override
    public Homework[] getHomeworksOfTeacher() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        String userId = claims.get("id").toString();
        Homework[] homeworkOfTeacher = teacherMapper.getHomeworkOfTeacher(userId);
        if (homeworkOfTeacher.length >= 1) {
            log.info("用户【" + userId + "】获取了 " + homeworkOfTeacher.length + " 条成绩信息：" + Arrays.toString(homeworkOfTeacher));
            return homeworkOfTeacher;
        }
        return null;
    }

    @Override
    public SignIn[] getSignIns() {


        return new SignIn[0];
    }

    @Override
    public int CommentStudentHomework(Homework homework) {
        return teacherMapper.CommentStudentHomework(homework);
    }

    @Override
    public int ChangeHomework(String expId, String fileCompletePath) {
        return teacherMapper.changeHomework(expId,fileCompletePath);
    }

    @Override
    public SubjectVO[] getSubjects() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        String userId = claims.get("id").toString();
        return teacherMapper.getSubjects(userId);
    }

    @Override
    public int changeWeight(SubjectVO subjectVO) {
        return teacherMapper.changeWeight(subjectVO);
    }

    @Override
    public int cancleSignIns(String subjectId) {
        log.info("用户取消了签到");
        Map<String, Object> claims = ThreadLocalUtil.get();
        String userId = claims.get("id").toString();
        SignIn sign = new SignIn();
        sign.setUserId(userId);
        sign.setSubjectId(subjectId);
        teacherMapper.updateTotalPoints(sign,-10.0);
        teacherMapper.updateLog(sign);
        teacherMapper.updatePoints(sign,-10.0);
        return teacherMapper.cancleSignIns(subjectId);
    }


    //选择科目时验证是否有科目权限。
    public static boolean containsSubjectId(CheckPOJO[] subs, String targetSubjectId, int i) {
        if (!(subs.length >= 1)) return false;
        for (CheckPOJO sub : subs) {
            switch (i) {
                case 0 -> {
                    if (targetSubjectId.equals(sub.getHomeworkId())) {
                        return true;
                    }
                }
                case 1 -> {
                    if (targetSubjectId.equals(sub.getSubjectId()))
                        return true;
                }
            }
        }
        return false;
    }
}
